import WebHeader from '@/www/components/WebHeader'
import WebFooter from '@/www/components/WebFooter'
import { getQuote, uploadFile, postQuoteOrder } from '@/apiv2/quote'
import yun from '@/utils/yun'

const CODE = 'ColorPage'

export default {
  components: { WebHeader, WebFooter },
  data() {
    return {
      gramData: undefined,//克重对应表
      quoteData: undefined,
      checkValue: {
        flagLamination: false,//覆膜
        flagFoldedPage: false,//折页
        flagPressLine: false,//压线
        flagNumber: false,//打号码
        flagPinholeThread: false,//针孔线
        flagShipping:false,//毛边出货
        flagCut:false,//切成品
      },

      quoteValue: {
        numberCount: '1',
        pressLine: '1',
        category: undefined,
        lamination: 'matteFilm',
        style: 1,
        side: '单面',
        laminationSide: '1',
        quantity: undefined,
        customQuantity: undefined,
        size: undefined,
        customLength: undefined,
        customWidth: undefined,
      },

      processSelectOptions: {
        laminationSide: [
          {value: '1', label: '单面'},
          {value: '2', label: '双面'},
        ],
        lamination: [
          {value: 'matteFilm', label: '覆哑膜'},
          {value: 'lightFilm', label: '覆亮膜'},
        ],
        pressLine: [
          {value: '1', label: '单向'},
          {value: '2', label: '横向竖向'},
        ],
        number: [
          {value: '1', label: '1个'},
          {value: '1.5', label: '2个'},
        ],
      },

      user: undefined,
      customSize: false,
      quote: undefined,
      quoteList: undefined,
      detail: undefined,
      fileList: [],
      logic: undefined,
      postData: {
        quantity: undefined,
        detail: undefined,
        amount: undefined,
        fileIds: undefined
      },
      note: undefined
    }
  },

  created(){
    const user = JSON.parse(localStorage.getItem('user'))
    this.user = user

    getQuote(CODE).then(res => {
      let quoteData = res.config
      this.quoteValue.category = quoteData.cateData.list[0]
      this.quoteValue.size = quoteData.sizeData.list[0].name
      this.quoteValue.quantity = quoteData.stepData.list[0]
      this.quoteValue.foldedPage = quoteData.process.foldedPagePriceList[0].name

      let gramData = {}
      const REG = /\d+/;
      quoteData.cateData.list.forEach(item => {
        let gram = parseInt(item.match(REG)[0].replace('g',''))
        gramData[item] = gram
      })

      this.gramData = gramData
      this.quoteData = quoteData
    })
  },

  methods: {

    //获取最终尺寸
    getFinalSize(){
      let {quoteValue,customSize} = this
      let length = undefined
      let width = undefined
      if(quoteValue.customLength && quoteValue.customWidth && customSize){
        length = parseInt(quoteValue.customLength)
        width = parseInt(quoteValue.customWidth)
      }else if(quoteValue.size){
        let sizeStr = quoteValue.size.match(/\d+\*\d+/)[0]
        length = parseInt(sizeStr.split('*')[0])
        width = parseInt(sizeStr.split('*')[1])
      }
      return {
        length: length,
        width: width
      }
    },

    onCategoryChange(){
      this.checkValue.flagFoldedPage = false
      this.checkValue.flagPressLine = false
    },

    onFlagFoldedPageChange(){
      if(this.checkValue.flagFoldedPage){
        if(this.gramData[this.quoteValue.category] > 200){
          this.$message.error('折页材料不能大于200g')
          this.checkValue.flagFoldedPage = false
          return
        }

        if(this.customSize && (!quoteValue.customLength || !quoteValue.customWidth)){
          this.$message.error('请输入自定义尺寸')
          this.checkValue.flagFoldedPage = false
          return
        }

        let {length,width} = this.getFinalSize()
        if(yun.ifPageAreaBiggerThan(length+'*'+width,yun.PAPER_INFO.A2.size) || yun.ifPageAreaBiggerThan(length+'*'+width,yun.PAPER_INFO.A2L.size)){
          this.$message.error('折页尺寸不能超过A2或者长A2')
          this.checkValue.flagFoldedPage = false
          return
        }
      }
    },

    onFlagPressLineChange(){
      if(this.checkValue.flagPressLine){
        if(this.gramData[this.quoteValue.category] < 200){
          this.$message.error('压线材料最少需要200g')
          this.checkValue.flagPressLine = false
        }
      }
    },

    //自定义尺寸切换
    onCustomSizeToggle(){
      this.checkValue.flagNumber = false
      this.quoteValue.customLength = undefined
      this.quoteValue.customWidth = undefined
    },

    //判断输入尺寸是否系小于或者等于A3或者长A3
    checkIsLessOrEqualThanA3(length,width){
      let flag = false
      let long = undefined
      let short = undefined
      if(length >= width){
        long = length
        short = width
      }else{
        long = width
        short = length
      }

      if((long <= 420 && short <= 285) || (long <= 570 && short <= 210)){
        flag = true
      }

      return flag
    },

    onFlagNumberOn(){
      let {quoteValue,customSize} = this

      if(customSize && (!quoteValue.customLength || !quoteValue.customWidth)){
        this.$message.error('请输入自定义尺寸')
        return
      }

      let {length,width} = this.getFinalSize()

      if(this.checkValue.flagNumber){
        if(!this.checkIsLessOrEqualThanA3(length,width)){
          this.$message.error('打号码尺寸必须小于A3')
          this.checkValue.flagNumber = false
        }
      }
    },

    checkCutShippingValue(name,target){
      if(this.checkValue[name]){
        this.checkValue[target] = false
      }
    },

    selectQuantity(){
      if(this.quoteValue.quantity){
        this.quoteValue.customQuantity = undefined
      }
    },

    customQuantity(){
      if(this.quoteValue.customQuantity){
        this.quoteValue.quantity = undefined
      }else{
        this.quoteValue.quantity = this.quoteData.stepData.list[0]
      }
    },

    caculateCountPerPage(len,width,customLen,customWidth){
      let a = 0
      let b = 0
      if(len >= customLen && width >= customWidth){
        a = parseInt(len / customLen) * parseInt(width / customWidth)
      }

      if(len >= customWidth && width >= customLen){
        b = parseInt(len / customWidth) * parseInt(width / customLen)
      }

      return a >= b ? a : b
    },

    getQuantityRangePrice(quantity,list){
      for(let i=0;i<list.length;i++){
        if(quantity >= parseInt(list[i].start) && quantity <= list[i].end){
          return parseFloat(list[i].price)
        }
      }
    },

    getQuote(){
      let {quoteData,quoteValue,checkValue,customSize,postData} = this

      if(customSize && (!quoteValue.customLength || !quoteValue.customWidth)){
        this.$message.error('请输入自定义尺寸')
        return
      }

      const CATEGORY_GRAM = parseInt(quoteValue.category.match(/\d+g/)[0])//材料克重
      const GRAM_SUFFIX = (CATEGORY_GRAM >= 200 ? '_200' : '')//克重匹配后缀

      const A5_AREA = 210 * 140
      const A4_AREA = 210 * 285
      const A3_AREA = 420 * 285
      const LA3_AREA = 210 * 570
      const SA2_AREA = 285 * 630
      const A2_AREA = 420 * 570
      const LA2_AREA = 285 * 840
      const A1_AREA = 840 * 570

      let detail = ''

      let length = undefined
      let width = undefined
      if(quoteValue.customLength && quoteValue.customWidth && customSize){
        length = parseInt(quoteValue.customLength)
        width = parseInt(quoteValue.customWidth)
      }else if(quoteValue.size){
        let sizeStr = quoteValue.size.match(/\d+\*\d+/)[0]
        length = parseInt(sizeStr.split('*')[0])
        width = parseInt(sizeStr.split('*')[1])
      }

      const AREA = length * width
      let finalSize = undefined
      let countPerPage = undefined
      let pageName = undefined
      const AREA_SQUARE = (parseFloat(length) * parseFloat(width)) / parseFloat(1000000).toFixed(8)

      if(customSize){
        if(AREA <= A5_AREA){
          pageName = 'A5(210*140)'
          finalSize = '210*140'
          countPerPage = this.caculateCountPerPage(210,140,length,width)
        }else if(AREA > A5_AREA && AREA <= A4_AREA){
          pageName = 'A4(210*285)'
          finalSize = '210*285'
          countPerPage = this.caculateCountPerPage(210,285,length,width)
        }else if(AREA > A4_AREA && AREA <= A3_AREA){
          pageName = 'A3(420*285)'
          finalSize = '420*285'
          countPerPage = this.caculateCountPerPage(420,285,length,width)
        }else if(AREA > LA3_AREA && AREA <= LA3_AREA){
          pageName = '长A3(210*570)'
          finalSize = '210*570'
          countPerPage = this.caculateCountPerPage(210,570,length,width)
        }else if(AREA > SA2_AREA && AREA <= SA2_AREA){
          pageName = '小A2(285*630)'
          finalSize = '285*630'
          countPerPage = this.caculateCountPerPage(285,630,length,width)
        }else if(AREA > A2_AREA && AREA <= A2_AREA){
          pageName = 'A2(420*570)'
          finalSize = '420*570'
          countPerPage = this.caculateCountPerPage(420,570,length,width)
        }else if(AREA > LA2_AREA && AREA <= LA2_AREA){
          pageName = '长A2(285*840)'
          finalSize = '285*840'
          countPerPage = this.caculateCountPerPage(285,840,length,width)
        }else if(AREA > A1_AREA && AREA <= A1_AREA){
          pageName = 'A1(840*570)'
          finalSize = '840*570'
          countPerPage = this.caculateCountPerPage(840,570,length,width)
        }
      }else{
        pageName = quoteValue.size
        finalSize = quoteValue.size
        countPerPage = 1
      }

      detail += '尺寸' + length + '*' + width +'，'
        + quoteValue.category +'，'
        + quoteValue.style + '款，'
        + quoteValue.side + '，'
      this.note = pageName + '拼' + countPerPage + '个'

      let finalPageItem = undefined
      quoteData.sizeData.list.forEach(item => {
        if(pageName == item.name){
          finalPageItem = item
        }
      })

      let quoteList = []

      if(true){
        if(checkValue.flagLamination){
          if('matteFilm' == quoteValue.lamination){
            detail += quoteValue.laminationSide == '1' ? '单面哑膜，' : '双面哑膜，'
          }else if('lightFilm' == quoteValue.lamination){
            detail += quoteValue.laminationSide == '1' ? '单面光膜，' : '双面光膜，'
          }
        }

        if(checkValue.flagPressLine){
          detail += '压线(' + (quoteValue.pressLine == '1' ? '单向)，' : '横向竖向)，')
        }

        if(checkValue.flagFoldedPage){
          detail += quoteValue.foldedPage + '，'
        }

        if(checkValue.flagNumber){
          detail += '打号码(' + (quoteValue.numberCount == '1' ? '1个)，' : '2个)，')
        }

        if(checkValue.flagPinholeThread){
          detail += '啤针孔线，'
        }

        if(checkValue.flagCut){
          detail += '切成品，'
        }

        if(checkValue.flagShipping){
          detail += '毛边出货，'
        }
      }

      let finalQantity = this.quoteValue.quantity ? parseInt(this.quoteValue.quantity) : parseInt(this.quoteValue.customQuantity)
      detail += finalQantity + '张'

      let defaultFlag = false

      let stepList = []

      postData.detail = detail

      quoteData.stepData.list.forEach(i => {
        const QTY = parseInt(i)//阶梯张数
        stepList.push(QTY)

        let pageCount = Math.ceil(QTY / countPerPage)

        let priceItem = undefined
        for(let i=0;i<quoteData.skuList.length;i++){
          let item = quoteData.skuList[i]
          if(quoteValue.category == item.name && pageCount <= parseInt(item.quantity)){
            priceItem = item
            break
          }
        }

        const MATERIAL_AMOUNT = Math.ceil(parseFloat(priceItem.price) * parseFloat(finalPageItem.multiple)) * parseFloat(quoteValue.style)

        let processAmount = 0

        if(checkValue.flagLamination){
          let totalLanPrice = undefined
          if(quoteValue.lamination == 'matteFilm'){
            let lanPrice = this.getQuantityRangePrice(QTY,quoteData.process.matteFilmRangePrice)
            totalLanPrice = AREA_SQUARE * QTY * lanPrice
            totalLanPrice = totalLanPrice > parseFloat(quoteData.process.matteFilmStartPrice) ? totalLanPrice : parseFloat(quoteData.process.matteFilmStartPrice)
          }else if(quoteValue.lamination == 'lightFilm'){
            let lanPrice = this.getQuantityRangePrice(QTY,quoteData.process.lightFilmRangePrice)
            totalLanPrice = AREA_SQUARE * QTY * lanPrice
            totalLanPrice = totalLanPrice > parseFloat(quoteData.process.lightFilmStartPrice) ? totalLanPrice : parseFloat(quoteData.process.lightFilmStartPrice)
          }
          processAmount += totalLanPrice * parseFloat(quoteValue.style) * parseFloat(quoteValue.laminationSide)
        }

        if(checkValue.flagPressLine){
          if(QTY <= parseInt(quoteData.process.pressLineStartQuantity)){
            processAmount += parseFloat(quoteData.process.pressLineStartPrice) * parseFloat(quoteValue.style) * parseFloat(quoteValue.pressLine)
          }else{
            let count = parseFloat((QTY - parseInt(quoteData.process.pressLineStartQuantity)) / parseInt(quoteData.process.pressLineStartQuantity))
            let pressLinePrice = parseFloat(quoteData.process.pressLineStartPrice)
              + parseFloat(quoteData.process.pressLinePerPrice) * count
            pressLinePrice = pressLinePrice > parseFloat(quoteData.process.pressLineStartPrice) ? pressLinePrice : parseFloat(quoteData.process.pressLineStartPrice)
            processAmount += pressLinePrice * parseFloat(quoteValue.style) * parseFloat(quoteValue.pressLine)
          }
        }

        if(checkValue.flagFoldedPage){
          let foldedPagePriceItem = undefined
          let foldedPageAmount = undefined
          for(let i=0;i<quoteData.process.foldedPagePriceList.length;i++){
            let item = quoteData.process.foldedPagePriceList[i]
            if(item.name == quoteValue.foldedPage){
              foldedPagePriceItem = item
              break
            }
          }
          if(QTY <= 500){
            foldedPageAmount = parseFloat(foldedPagePriceItem['startPrice' + GRAM_SUFFIX]) * parseFloat(quoteValue.style)
          }else{
            let count = parseFloat((QTY - 500) / 500)
            let foldedPagePrice = parseFloat(foldedPagePriceItem['startPrice' + GRAM_SUFFIX])
              + parseFloat(foldedPagePriceItem['price' + GRAM_SUFFIX]) * count
            foldedPagePrice = foldedPagePrice > parseFloat(foldedPagePriceItem['startPrice' + GRAM_SUFFIX]) ? foldedPagePrice : parseFloat(foldedPagePriceItem['startPrice' + GRAM_SUFFIX])
            foldedPageAmount = foldedPagePrice * parseFloat(quoteValue.style)
          }

          let foldedPageDiscount = 1
          for(let i = 0; i < quoteData.process.foldedPageDiscountList.length; i++){
            let item = quoteData.process.foldedPageDiscountList[i]
            if(QTY >= parseInt(item['start']) && QTY <= parseInt(item['end'])){
              foldedPageDiscount = parseFloat(item['discount'])
              break
            }
          }
          processAmount += foldedPageAmount * foldedPageDiscount
        }

        if(checkValue.flagNumber){
          if(QTY <= 500){
            processAmount += parseFloat(quoteData.process.codeStartPrice) * parseFloat(quoteValue.style) * parseFloat(quoteValue.numberCount)
          }else{
            let count = parseFloat((QTY - 500) / 500)
            let codePrice = parseFloat(quoteData.process.codeStartPrice)
              + parseFloat(quoteData.process.codePerPrice) * count
            codePrice = codePrice > parseFloat(quoteData.process.codeStartPrice) ? codePrice : parseFloat(quoteData.process.codeStartPrice)
            processAmount += codePrice * parseFloat(quoteValue.style) * parseFloat(quoteValue.numberCount)
          }
        }

        if(checkValue.flagPinholeThread){
          if(QTY <= 500){
            processAmount += parseFloat(quoteData.process.pinholeThreadStartPrice) * parseFloat(quoteValue.style)
          }else{
            let count = parseFloat((QTY - 500) / 500)
            let pinholeThreadPrice = parseFloat(quoteData.process.pinholeThreadStartPrice)
              + parseFloat(quoteData.process.pinholeThreadPerPrice) * count
            pinholeThreadPrice = pinholeThreadPrice > parseFloat(quoteData.process.pinholeThreadStartPrice) ? pinholeThreadPrice : parseFloat(quoteData.process.pinholeThreadStartPrice)
            processAmount += pinholeThreadPrice * parseFloat(quoteValue.style)
          }
        }

        const AMOUNT = parseInt(MATERIAL_AMOUNT) + parseInt(processAmount)


        if(finalQantity == parseInt(i)){
          postData.amount = AMOUNT
          defaultFlag = true
        }

        quoteList.push({
          quantity: QTY,
          materialAmount: parseInt(MATERIAL_AMOUNT),
          processAmount: parseInt(processAmount),
          totalAmount: AMOUNT

        })

        this.quoteList = quoteList
      })

      if(!defaultFlag){
        let index = undefined
        let target = parseInt(finalQantity)
        let farr = []
        for(let i=(stepList.length-1);i > -1;i--){
          if(target < stepList[i]){
            continue
          }
          if(!index){
            index = i
          }
          let m = target % stepList[i]
          farr.push({
            quantity: stepList[i],
            count: parseInt(target / stepList[i])
          })
          if(m == 0){
            break
          }else{
            target = m
          }
        }

        let finalMaterialAmount = 0
        let finalProcessAmount = 0

        for(let i=0;i<quoteList.length;i++){
          let item = quoteList[i]
          for(let j=0;j<farr.length;j++){
            if(item.quantity == farr[j].quantity){
              finalMaterialAmount += item.materialAmount * farr[j].count
              finalProcessAmount += item.processAmount * farr[j].count
            }
          }
        }
        quoteList.splice(index + 1,0,{
          quantity: finalQantity,
          materialAmount: parseInt(finalMaterialAmount),
          processAmount: parseInt(finalProcessAmount),
          totalAmount: parseInt(finalMaterialAmount) + parseInt(finalProcessAmount)
        })
        postData.amount = parseInt(finalMaterialAmount) + parseInt(finalProcessAmount)
        this.quoteList = quoteList
        this.postData = postData
      }
    },

    submitOrder(){
      const {fileList,postData} = this

      if(fileList.length < 1){
        this.$message.error('请上传设计稿')
        return
      }

      let fileIds = [];
      fileList.forEach(item => {
        fileIds.push(item.id)
      })
      postData.fileIds = fileIds

      const loading = this.$loading({
        lock: true,
        text: '正在创建订单',
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.7)'
      });

      postQuoteOrder(postData).then(res => {
        loading.close()
        this.$message.success('成功创建订单')
        this.$router.push({
          path: '/submitOrder',
          query: { id : res.id}
        })
      }).catch(err => {
        loading.close()
        this.$message.error('创建订单失败')
      })
    },

    handleUpload: async function(data){
      const formData = new FormData()
      formData.append('file', data.file)
      const res = await uploadFile(formData)
      let fileList = this.fileList
      fileList.push(res.file)
      this.fileList = fileList
    }
  }
}
